package com.hsck.order.kds.main.fragment.order

import android.app.Activity
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.AsyncListDiffer
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.hsck.order.kds.R
import com.hsck.order.kds.base.isnoam.log.XFrame
import com.hsck.order.kds.base.utils.calculateMinutesSinceOrder
import com.hsck.order.kds.base.utils.setOnSingleClickListener
import com.hsck.order.kds.base.isnoam.view.CustomDividerItemDecoration
import com.hsck.order.kds.databinding.OrderDynamicsItemLayoutBinding
import com.hsck.order.kds.main.fragment.standard.bean.DishManager
import com.hsck.order.kds.main.fragment.standard.bean.TestListBean
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.delay
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch

class OrderDynamicsAdapter(
    val activity: Activity,
    private val columns: Int,
) : RecyclerView.Adapter<OrderDynamicsAdapter.ItemVH>() {

    private val coroutineScope = CoroutineScope(Dispatchers.Main + SupervisorJob())
    private val viewHolders = mutableListOf<ItemVH>()
    private var parentPosition = 0
    private var orderDynamicsDishItemsAdapters: MutableList<OrderDynamicsDishItemsAdapter> =
        mutableListOf()
    private val diffUtil = object : DiffUtil.ItemCallback<TestListBean>() {
        override fun areItemsTheSame(oldItem: TestListBean, newItem: TestListBean): Boolean {
            return oldItem.id == newItem.id
        }

        override fun areContentsTheSame(oldItem: TestListBean, newItem: TestListBean): Boolean {
            return oldItem == newItem
        }
    }
    private val asyncListDiffer = AsyncListDiffer(this, diffUtil)

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ItemVH {
        val viewHolder = ItemVH(
            OrderDynamicsItemLayoutBinding.inflate(
                LayoutInflater.from(parent.context), parent, false
            )
        )
        val spacingInPixels = activity.resources.getDimensionPixelSize(R.dimen.four_column_spacing)
        val totalSpacing = spacingInPixels * (columns - 1) // 4 列需要 3 个间距
        val itemWidth = (parent.width - totalSpacing) / columns
        val layoutParams = viewHolder.itemView.layoutParams
        layoutParams.width = itemWidth
        viewHolder.itemView.layoutParams = layoutParams
        viewHolders.add(viewHolder)
        return viewHolder
    }

    inner class ItemVH(val binding: OrderDynamicsItemLayoutBinding) :
        RecyclerView.ViewHolder(binding.root) {

        private var updateJob: Job? = null
        private var time = 0

        fun bindData(position: Int) {
            val item = asyncListDiffer.currentList[position]
            binding.tvTime.text = calculateMinutesSinceOrder(item.time).toString()

            if (orderDynamicsDishItemsAdapters.size <= position) {
                orderDynamicsDishItemsAdapters.add(OrderDynamicsDishItemsAdapter(activity))
            }
//            val orderDynamicsDishItemsAdapter = orderDynamicsDishItemsAdapters[position]
            val orderDynamicsDishItemsAdapter = OrderDynamicsDishItemsAdapter(activity)
            initRecyclerView(binding, position, orderDynamicsDishItemsAdapter)
            itemView.setOnSingleClickListener {
                onDishOperationListener.onDishOperationAction(item, position)
            }
            updateJob = coroutineScope.launch {
                while (isActive) {
//                    val time = calculateMinutesSinceOrder(item.time)
                    time = calculateMinutesSinceOrder(item.time)
                    binding.tvTime.text = "$time'"
                    if (time <= 10) {
                        orderDynamicsDishItemsAdapter.setTextColor(0)
                        if (binding.constraintStatus.tag != "enchanting") {
                            binding.constraintStatus.background =
                                XFrame.getDrawable(R.drawable.order_dynamics_zhengchang_bg_shape)
                            binding.constraintStatus.tag = "enchanting"
                        }
                    } else if (time in 11..19) {
                        orderDynamicsDishItemsAdapter.setTextColor(1)
                        if (binding.constraintStatus.tag != "ring") {
                            binding.constraintStatus.background =
                                XFrame.getDrawable(R.drawable.order_dynamics_yujing_bg_shape)
                            binding.constraintStatus.tag = "ring"
                        }
                    } else {
                        orderDynamicsDishItemsAdapter.setTextColor(2)
                        if (binding.constraintStatus.tag != "chaos") {
                            binding.constraintStatus.background =
                                XFrame.getDrawable(R.drawable.order_dynamics_chaoshi_bg_shape)
                            binding.constraintStatus.tag = "chaos"
                        }
                    }

                    delay(1000)
                }
            }
        }

        private fun initRecyclerView(
            binding: OrderDynamicsItemLayoutBinding,
            position: Int,
            orderDynamicsDishItemsAdapter: OrderDynamicsDishItemsAdapter,
        ) {
            val layoutManager = LinearLayoutManager(activity)
            binding.recyclerView.layoutManager = layoutManager
            layoutManager.isItemPrefetchEnabled = true
            binding.recyclerView.addItemDecoration(CustomDividerItemDecoration(activity))
            binding.recyclerView.adapter = orderDynamicsDishItemsAdapter
            binding.recyclerView.itemAnimator = null//关闭默认动画
            orderDynamicsDishItemsAdapter.submitList(DishManager().getTenItemDishList())
            orderDynamicsDishItemsAdapter.setDishOperationItemClickListener(object :
                OrderDynamicsDishItemsAdapter.DishOperationItemClickListener {
                override fun onDishOperationItemClick(
                    itemBean: TestListBean,
                    childPosition: Int,
                    childListSize: Int,
                ) {
                    this@OrderDynamicsAdapter.parentPosition = position
                    onDishOperationListener.onBatchDishAction(itemBean, position)/*onDishOperationListener.onSingleItemSelectionAction(
                                itemBean,
                                childPosition,
                                childListSize,
                                orderDynamicsDishItemsAdapter
                            )*/
                }
            })
        }

        fun stopUpdating() {
            updateJob?.cancel()
            updateJob = null
        }
    }

    fun removeItemAfterIndex(
        childPosition: Int,
        adapter: OrderDynamicsDishItemsAdapter,
        childListSize: Int,
    ) {
        adapter.removeItemAfterIndex(childPosition)
        if (childListSize == 0) {
            removeItemAfterIndex(parentPosition)
        }
    }

    fun submitList(dataResponse: List<TestListBean>) {
        asyncListDiffer.submitList(dataResponse)
    }

    fun addItemAfterId(newItem: TestListBean, targetId: String) {
        val newList = asyncListDiffer.currentList.toMutableList()
        val targetIndex = newList.indexOfFirst { it.id == targetId }
        if (targetIndex != -1) {
            newList.add(targetIndex, newItem)
            asyncListDiffer.submitList(newList)
        }
    }

    fun removeItemAfterId(targetId: String) {
        val newList = asyncListDiffer.currentList.toMutableList()
        val targetIndex = newList.indexOfFirst { it.id == targetId }
        if (targetIndex != -1) {
            newList.removeAt(targetIndex)
            asyncListDiffer.submitList(newList)
        }
    }

    fun removeItemAfterIndex(targetIndex: Int) {
        if (targetIndex < asyncListDiffer.currentList.size) {
            val newList = asyncListDiffer.currentList.toMutableList()
            newList.removeAt(targetIndex)
            asyncListDiffer.submitList(newList)
        }
    }


    fun stopAllUpdating() {
        for (holder in viewHolders) {
            holder.stopUpdating()
        }
    }

    override fun onViewRecycled(holder: ItemVH) {
        super.onViewRecycled(holder)
        holder.stopUpdating()
        viewHolders.remove(holder)
    }

    override fun onBindViewHolder(holder: ItemVH, position: Int) {
        holder.bindData(position)
    }

    override fun getItemCount(): Int {
        return asyncListDiffer.currentList.size
    }

    private lateinit var onDishOperationListener: DishOperationListener
    fun setDishOperationListener(onDishOperationListener: DishOperationListener) {
        this.onDishOperationListener = onDishOperationListener
    }

    interface DishOperationListener {
        //整单划菜
        fun onDishOperationAction(itemBean: TestListBean, position: Int)

        //批量划菜
        fun onBatchDishAction(itemBean: TestListBean, position: Int)

        //单品划菜
        fun onSingleItemSelectionAction(
            itemBean: TestListBean,
            childPosition: Int,
            childListSize: Int,
            adapter: OrderDynamicsDishItemsAdapter,
        )
    }
}